<?php
# CURL
namespace app\server;

class Curl extends Server
{
    // POST请求
    static public function post($host, $data = [], $header = [], $contentType = 1)
    {
        // 初始化
        $ch = curl_init();

        // 请求地址
        curl_setopt($ch, CURLOPT_URL, $host);
        // 返回结果(不直接输出)
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        // 不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

        // 超时时间 (连接成功后接收数据的超时时间)
        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
        // 超时时间 (尝试连接的超时时间)
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);

        // POST请求
        curl_setopt($ch, CURLOPT_POST, 1);

        // 请求头
        $headerData = array();
        if (!empty($header)) {
            foreach ($header as $key => $val) {
                $headerData[] = $key . ':' . $val;
            }
        }

        // 数据格式
        if ($contentType == 1) {
            $headerData[] = 'Content-Type:application/json';
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
        if ($contentType == 2) {
            $headerData[] = 'Content-Type:application/x-www-form-urlencoded';
            if (!empty($data)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
            }
        }
        if ($contentType == 3) {
            $headerData[] = 'Content-Type: multipart/form-data';
            if (!empty($data)) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            }
        }

        // 设置请求头
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerData);

        // 执行请求
        $result = curl_exec($ch);

        // 获取请求状态
        $errNum = curl_errno($ch);

        // 结果
        $res = array();

        // 是否请求成功 0成功
        if ($errNum === 0) {
            $res['code'] = $errNum;
            $res['data'] = $result;
        } else {
            $res['code'] = $errNum;
            $res['data'] = curl_error($ch);
        }

        // 关闭资源
        curl_close($ch);

        // 返回结果
        return $res;
    }

}
